import React from 'react';
import styled from 'styled-components';

import { Bank } from '../../basis-cash';
import Button from '../../components/Button';
import Card from '../../components/Card';
import CardContent from '../../components/CardContent';
import CardIcon from '../../components/CardIcon';
import useBanks from '../../hooks/useBanks';
import TokenSymbol from '../../components/TokenSymbol';
import Notice from '../../components/Notice';

import title_mdex from '../../assets/image/title_mdex.png';
import title_mdex_lava from '../../assets/image/title_mdex_lava.png';
import icon_left from '../../assets/image/icon_left.png';

import useBasisCash from '../../hooks/useBasisCash';
import config from '../../config';

import img_yeqian from '../../assets/image/img_yeqian.png';
import { getDisplayBalance } from '../../utils/formatBalance';

export interface IOfferingBadgeBaseProps {
  counts?: number;
  setCount?: Function;
  stakedOnly?: boolean;
}

const BankCards: React.FC<IOfferingBadgeBaseProps> = props => {
  const [banks] = useBanks();
  const basisCash = useBasisCash();

  const {counts,setCount} = props;

 
  // const activeBanks = banks.filter((bank) => !bank.finished);
  const activeBanks = banks.filter((bank) => (!bank.finished&&bank.earnTokenName == 'SHARE'&&bank.group == config.group)  );
  const inactiveBanks = banks.filter((bank) => bank.finished&&bank.group == config.group);

  // console.log('newBankRows',activeBanks)

  let finishedFirstRow = false;
  const inactiveRows = inactiveBanks.reduce<Bank[][]>(
    (bankRows, bank) => {
      const newBankRows = [...bankRows];
      if (newBankRows[newBankRows.length - 1].length === (finishedFirstRow ? 2 : 3)) {
        newBankRows.push([bank]);
        finishedFirstRow = true;
      } else {
        newBankRows[newBankRows.length - 1].push(bank);
      }
      return newBankRows;
    },
    [[]],
  );

  const func = async ()=>{
    console.log('banksbanksbanks',activeBanks)
    let bbc = 0;
    for (const iterator of activeBanks) {
      console.log('===============' + iterator.depositToken);
    await basisCash.getTVL2(iterator.depositToken.address)
    .then(res=>{
      bbc+=parseInt(res);
    })
    }
    setCount(bbc)
  }

  React.useEffect(()=>{
    func();
  },[config.group]);


  return (
    <StyledCards>
      <StyledCards1>
      <img
        src={config.group == 'cash' ? title_mdex_lava : title_mdex}
        alt={`title_mdex Logo`}
        style={{width: '100%', maxWidth: 320 }}
      />
      {/* {cunCounts} */}
      
      </StyledCards1>
      {inactiveRows[0].length > 0 && (
        <StyledInactiveNoticeContainer>
          <Notice color="grey">
            <b>You have banks where the mining has finished.</b>
            <br />
            Please withdraw and settle your stakes.
          </Notice>
        </StyledInactiveNoticeContainer>
      )}
      <StyledRow>
        {activeBanks.map((bank, i) => (
          <React.Fragment key={bank.name}>
            <BankCard bank={bank} stakedOnly={props.stakedOnly} />
          </React.Fragment>
        ))}
      </StyledRow>
      {inactiveRows[0].length > 0 && (
        <>
          <StyledInactiveBankTitle>Inactive Banks</StyledInactiveBankTitle>
          {inactiveRows.map((bankRow, i) => (
            <StyledRow key={i}>
              {bankRow.map((bank, j) => (
                <React.Fragment key={j}>
                  <BankCard bank={bank} />
                </React.Fragment>
              ))}
            </StyledRow>
          ))}
        </>
      )}
    </StyledCards>
  );
};

interface BankCardProps {
  bank: Bank;
  counts?: number;
  setCount?: Function;
  stakedOnly?: boolean;
}

  
const BankCard: React.FC<BankCardProps> = ({ bank,counts,setCount,stakedOnly }) => {
  const [apy,setApy] = React.useState('');
  const [apyy,setApyy] = React.useState('');
  React.useEffect(()=>{
    basisCash.getAPY2(bank.contract, bank.depositToken)
    .then(res=>{
      let num = (parseFloat(res)*100).toFixed(2);
      setApy(num+'%');
      setApyy((Math.min(999999, (Math.pow(1+(Number(num)/100)/365, 365)-1)*100)).toFixed(2) + '%');
    })
  },[]);
  const [staked, setStaked] = React.useState(false);
  const [tvl,setTvl] = React.useState('');
  React.useEffect(()=>{
    basisCash.getTVLPre(bank.depositToken.address, bank.contract, bank.depositTokenName)
    .then(res=>{
      setTvl(parseInt(res)+'');
    });
  },[]);

  React.useEffect(() => {
    if (stakedOnly) {
      basisCash.stakedBalanceOnBank(bank.contract, basisCash.myAccount).then(res => {
        if (Number(getDisplayBalance(res, bank.depositToken.decimal)) > 0) {
          setStaked(true);
        }
        console.log('staked', staked);
      });
    }
  }, [stakedOnly]);
  
  const basisCash = useBasisCash();

  const onlyStakeDisplay = stakedOnly && !staked ? 'none' : 'block';

  return (
    <StyledCardWrapper style={{display: `${onlyStakeDisplay}`}}>
      {/* {bank.depositTokenName.includes('LP') &&
        (bank.depositTokenName.includes('BAS_DAI') ? (
          <StyledCardSuperAccent />
        ) : (
          <StyledCardAccent />
        ))} */}
        <StyledCardSuperAccent />
      <Card>
        <CardContent>
          <StyledContent>
            {
              bank.contract == 'LavaPool_SHARE'
              ?
              <></>
              :
              <div style={{position:'absolute', display: 'flex', justifyContent: 'center', alignItems: 'center', top:'-24px', right:'-32px', zIndex: 0,  color: '#fff', fontSize: '14px'}}>
                  <img
                src={img_yeqian}
                width={80}
                style={{ marginRight: '6px'}}
              />
              {bank.depositTokenName == 'sCASH_USDT_LP'?<Xiezi>x40</Xiezi>: <></> }
              {bank.depositTokenName == 'sCASH_HUSD_LP'?<Xiezi>x40</Xiezi>: <></> }
              {bank.depositTokenName == 'SHARE_USDT_LP'?<Xiezi>x10</Xiezi>: <></> }
              {bank.depositTokenName == 'SHARE_HUSD_LP'?<Xiezi>x10</Xiezi>: <></> }


              {bank.depositTokenName == 'sHT_wHT_LP'?<Xiezi>x50</Xiezi>: <></> }
              {bank.depositTokenName == 'sHT_USDT_LP'?<Xiezi>x12.5</Xiezi>: <></> }
              {bank.depositTokenName == 'sHT_sCASH_LP'?<Xiezi>x12.5</Xiezi>: <></> }
              {bank.depositTokenName == 'SHARE_wHT_LP'?<Xiezi>x25</Xiezi>: <></> }

              {bank.depositTokenName == 'sNEO_pNEO_LP'?<Xiezi>x50</Xiezi>: <></> }
              {bank.depositTokenName == 'sNEO_USDT_LP'?<Xiezi>x12.5</Xiezi>: <></> }
              {bank.depositTokenName == 'sNEO_sCASH_LP'?<Xiezi>x12.5</Xiezi>: <></> }
              {bank.depositTokenName == 'SHARE_pNEO_LP'?<Xiezi>x25</Xiezi>: <></> }

              {bank.depositTokenName == 'sFILDA_FILDA_LP'?<Xiezi>x40</Xiezi>: <></> }
              {bank.depositTokenName == 'FILDA_sHT_LP'?<Xiezi>x40</Xiezi>: <></> }
              {bank.depositTokenName == 'SHARE_FILDA_LP'?<Xiezi>x20</Xiezi>: <></> }

              {bank.depositTokenName == 'sNULS_NULS_LP'?<Xiezi>x40</Xiezi>: <></> }
              {bank.depositTokenName == 'sCASH_NULS_LP'?<Xiezi>x40</Xiezi>: <></> }
              {bank.depositTokenName == 'SHARE_NULS_LP'?<Xiezi>x20</Xiezi>: <></> }
              
              
              </div>
            }
          
            <CardIcon>
              <TokenSymbol symbol={bank.depositTokenName} size={54} />
              <img
              src={icon_left}
              alt={`icon_left`}
              width={27}
              style={{marginLeft: 5, marginRight: 5}}
            />
            
              <TokenSymbol symbol={bank.earnTokenName} size={54} />
            </CardIcon>
            <StyledTitle>{bank.name}</StyledTitle>
            <StyledDetails>
              <StyledDetail>存入 {bank.depositTokenName}</StyledDetail>
              <StyledDetail>赚取 {`${bank.earnTokenName}`}</StyledDetail>
              <StyledDetail>锁仓量: ${`${tvl}`}</StyledDetail>
              <StyledDetail>年化收益率: {`${apy}`}</StyledDetail>
              <StyledDetail>复合年化收益率: {`${apyy}`}</StyledDetail>
            </StyledDetails>
            <Button text="选择" to={`/Nebula/${bank.contract}`} />
            <a target="_blank" href={`${config.etherscanUrl}/address/${bank.address}`} style={{fontSize: 10, marginTop: 12, color: '#fa4e32', textDecoration: 'none' }}>合约地址: {bank.address.substring(0,4) + '****'+ bank.address.substring(bank.address.length-4,bank.address.length)}</a>
          </StyledContent>
        </CardContent>
      </Card>
    </StyledCardWrapper>
  );
};

const StyledCardAccent = styled.div`
  background: linear-gradient(
    45deg,
    rgba(255, 0, 0, 1) 0%,
    rgba(255, 154, 0, 1) 10%,
    rgba(208, 222, 33, 1) 20%,
    rgba(79, 220, 74, 1) 30%,
    rgba(63, 218, 216, 1) 40%,
    rgba(47, 201, 226, 1) 50%,
    rgba(28, 127, 238, 1) 60%,
    rgba(95, 21, 242, 1) 70%,
    rgba(186, 12, 248, 1) 80%,
    rgba(251, 7, 217, 1) 90%,
    rgba(255, 0, 0, 1) 100%
  );
  border-radius: 12px;
  filter: blur(4px);
  position: absolute;
  top: -2px;
  right: -2px;
  bottom: -2px;
  left: -2px;
  z-index: -1;
`;

const Xiezi = styled.p`
position:absolute; top: 10px; right: 12px; transform: rotate(45deg);
min-width: 50px; text-align: center;
`

const StyledCardSuperAccent = styled.div`
  background: linear-gradient(
    45deg,
    rgba(255, 0, 0, 1) 0%,
    rgba(255, 154, 0, 1) 10%,
    rgba(208, 222, 33, 1) 20%,
    rgba(79, 220, 74, 1) 30%,
    rgba(63, 218, 216, 1) 40%,
    rgba(47, 201, 226, 1) 50%,
    rgba(28, 127, 238, 1) 60%,
    rgba(95, 21, 242, 1) 70%,
    rgba(186, 12, 248, 1) 80%,
    rgba(251, 7, 217, 1) 90%,
    rgba(255, 0, 0, 1) 100%
  );
  border-radius: 12px;
  filter: blur(8px);
  position: absolute;
  top: -4px;
  right: -4px;
  bottom: -4px;
  left: -4px;
  z-index: -1;
`;

const StyledCards1 = styled.div`
  display: flex;
  width: 100%;
  margin-top: 30px;
  flex-direction: row;
  align-items: start;
`;

const StyledCards = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 1000px;
  border: 1px solid #fa4e32;
  margin-top: 30px;
  padding: 0 30px;
  border-left: 10px solid #fa4e32;
  @media (max-width: 768px) {
    width: 100%;
    margin-top: 6px;
    padding: 0 0;
    box-sizing: border-box;
  }
`;

const StyledLoadingWrapper = styled.div`
  align-items: center;
  display: flex;
  flex: 1;
  justify-content: center;
`;

const StyledRow = styled.div`
  display: flex;
  width: 100%;
  justify-content: space-between;
  margin-bottom: ${(props) => props.theme.spacing[4]}px;
  flex-flow: row wrap;
  @media (max-width: 768px) {
    width: 100%;
    flex-flow: column nowrap;
    align-items: center;
  }
`;

const StyledCardWrapper = styled.div`
  display: flex;
  width: calc((900px - ${(props) => props.theme.spacing[4]}px * 2) / 3);
  position: relative;
  margin-top: 60px;
`;

const StyledTitle = styled.h4`
  color: ${(props) => props.theme.color.grey[200]};
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  margin: ${(props) => props.theme.spacing[2]}px 0 0;
  padding: 0;
`;

const StyledContent = styled.div`
  align-items: center;
  display: flex;
  flex-direction: column;
  position: relative;
`;

const StyledSpacer = styled.div`
  height: ${(props) => props.theme.spacing[4]}px;
  width: ${(props) => props.theme.spacing[4]}px;
`;

const StyledDetails = styled.div`
  margin-bottom: ${(props) => props.theme.spacing[5]}px;
  margin-top: ${(props) => props.theme.spacing[2]}px;
  text-align: center;
`;

const StyledDetail = styled.div`
  color: ${(props) => props.theme.color.grey[300]};
`;

const StyledInactiveNoticeContainer = styled.div`
  width: 598px;
  margin-bottom: ${(props) => props.theme.spacing[6]}px;
`;

const StyledInactiveBankTitle = styled.p`
  font-size: 24px;
  font-weight: 600;
  color: ${(props) => props.theme.color.grey[400]};
  margin-top: ${(props) => props.theme.spacing[5]}px;
  margin-bottom: ${(props) => props.theme.spacing[4]}px;
`;

export default BankCards;
